import React, { Component } from 'react';
import { Relax } from 'iflux2';
import Immutable, { List, Map } from 'immutable';
import { rewardRulesQL, orderObtainQL } from '../ql';
import { Form, Switch, InputNumber, Row, Col, Input, Select, Button, Checkbox, Alert, Tag, Radio, Table, message, Tooltip, Icon } from 'antd';
import noop from 'util/noop';
import classNames from 'classnames';
import float from 'util/float'
const FormItem = Form.Item;
const RadioGroup = Radio.Group;

const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 16 },
};


@Relax
class IntegralForm extends Component {

    constructor(props) {
        super(props);
    }

    static contextTypes = {
        location: React.PropTypes.object
    }

    static defaultProps = {
        settingInfo: {},
        obtainTradePay: {},
        orderObtain:orderObtainQL,//交易奖励积分规则
        rewardRules: rewardRulesQL,
        onRuleUpdate: noop,
        onSettingUpdate: noop,
        onSave: noop,
        integralObtainWorth:Map({})
    }
    /**
     * 积分奖励类型设置回调
     * 1:混合模式
     * 2:商品售价比例
     * 3:商品固定积分
     */
    onWayChange = (e) => {
        let { onSettingUpdate } = this.props;
        onSettingUpdate(Immutable.fromJS({ orderObtainType: e.target.value }));
    };
    //是否启用相关的积分奖励
    onObtainIsOpenChange = (e, record) => {
        let { onRuleUpdate } = this.props;
        Object.assign(record, { isOpen: e.target.checked ? 1 : 0 });
        onRuleUpdate(Immutable.fromJS(record));
    };
    //注册和登录奖励积分
    onObtainValChange = (value, record) => {
        let { onRuleUpdate } = this.props;
        Object.assign(record, { obtainVal: value });
        onRuleUpdate(Immutable.fromJS(record));
    };

    onHandleSubmit = (e) => {
        
        e.preventDefault();
        
        this.props.form.validateFields((err, values) => {
            if (err) {
                return;
            }
            this.props.onSave(values);
        })
    }

    render() {

        let { 
            settingInfo, 
            obtainTradePay, 
            rewardRules, 
            integralObtainWorth, 
            form, 
            onSave 
        } = this.props;
        const { getFieldDecorator } = form;
        //积分设置
        var switchField = getFieldDecorator('isOpenSetting', {
            valuePropName: 'checked',
            initialValue: 1 == settingInfo.get("isOpenSetting"),
        })(
            <Switch checkedChildren={'开'} unCheckedChildren={'关'} onChange={this.toggleShow} />
            );

        // 货到付款是否使用积分
       // let orderObtain = rewardRules.find(r => r.get("obtainType") == "order");
       // let orderObtainIsOpen = orderObtain ? orderObtain.get("isOpen") : "";
       // let orderObtainVal = orderObtain ? orderObtain.get("obtainVal") : "";
        //货到付款取消了
        // var grpIntegralField = getFieldDecorator('grpIntegral', {
        //     valuePropName: 'checked',
        //     initialValue: settingInfo.get("grpIntegral") == 1,
        // })(
        //     <Checkbox disabled={orderObtainIsOpen == 0}/>
        //     );

        // 积分抵用
        var tradePayField = getFieldDecorator('tradePay', {
            initialValue: obtainTradePay.get("obtainVal") || '',
        })(
            <InputNumber min={0} max={99} style={{ width: '100px' }} />
            );

        // 规则说明
        var ruleDescField = getFieldDecorator('ruleDescription', {
            initialValue: settingInfo.get("ruleDescription") || '',
            validateTrigger: "onBlur",
            rules: [
                {
                    min: 0, max: 500, type: "string", message: "限制0-500个字"
                }
            ]
        })(
            <Input type="textarea" placeholder="" autosize={{ minRows: 3, maxRows: 6 }} />
            );

        const columns = this.renderColumns();
        
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 20 },
        };
       
        let hideclass = classNames({
            "hide" : settingInfo.get('isOpenSetting') ? false : true
        })
        return <div className="pusht">
            <Form onSubmit={this.onHandleSubmit}>
                <FormItem
                    label="积分说明"
                    {...formItemLayout}
                >

                    <span className="ant-form-text">{integralObtainWorth.get('obtainVal')}积分=1元</span>

                </FormItem>
                <FormItem
                    label="积分设置"
                    {...formItemLayout}
                >
                    {switchField}
                    <span className="ant-form-text">开启后，用户可以通过注册、登录、交易等途径获得积分奖励，并能将积分按比例抵扣订单金额</span>

                </FormItem>
                <FormItem
                    className={hideclass}
                    label="积分奖励"
                    {...formItemLayout}
                >
                    <div style={{ maxWidth: 1000 }}>
                        <Table columns={columns} bordered dataSource={rewardRules.sortBy(r=>r.get('sortNum')).toJS()} pagination={false} />
                    </div>
                </FormItem>
                <FormItem
                    label="积分抵用"
                    className={hideclass}
                    {...formItemLayout}
                >

                    积分最多可抵用订单总额的&nbsp;{tradePayField}%
                    <span className="ant-form-text t-grayer">
                        用户可使用积分抵扣订单金额，最大抵扣比例介于0-99%之间
                    </span>
                </FormItem>

                <FormItem
                    className={hideclass}
                    label="规则说明"
                    {...formItemLayout}
                >
                    <div style={{ maxWidth: 600 }}>
                        {ruleDescField}
                    </div>
                </FormItem>
                <Row>
                    <Col span={18} offset={4}>
                        <div className="pusht">
                            <Button type="primary" htmlType="submit">保存</Button>
                        </div>
                    </Col>
                </Row>
            </Form>
        </div>;
    }

    renderColumns = () =>{
        const { settingInfo, form, orderObtain, integralObtainWorth } = this.props;

        let orderObtainVal = orderObtain.get("obtainVal") || 0;
        /**
         * 示例里的价格，需要根据用户设置比例，作相应调整计算
         */
        const tempPrice =  200;
        //获得相应积分
        const tempObtainVal = Number(orderObtainVal/100 * tempPrice).toFixed(2);
        //积分与钱的比例
        const tempPercent = Number(tempObtainVal / integralObtainWorth.get('obtainVal')).toFixed(2)
        // 积分抵扣类型
        let obtainTypes = [
            { type: 1, key: "a", title: "商品售价比例", desc: `当前比例设置为${orderObtainVal}。`, demo: `商品A售价${tempPrice}元，买家购买1件A商品可获得${tempObtainVal}积分(价值${tempPercent}元)` },
            { type: 2, key: "b", title: "商品固定积分", desc: "按商品上面设置的固定积分，若固定积分未设置，则不返积分。", demo: "商品A售价200元，但是设置了固定积分60，买家在购买1件A商品时只可获得60积分(价值0.6元)" },
            { type: 3, key: "c", title: "混合模式", desc: "固定积分优先，若商品未设置固定积分则按照售价比例返积分", demo: "商品A售价200元，设置了固定积分60，商品B售价也是200元，但是未设置固定积分，买家购买1件A商品可获得60积分，购买一件B商品可获得100积分" }
        ]
        const orderObtainTypeField = form.getFieldDecorator('orderObtainType', {
            initialValue: settingInfo.get("orderObtainType"),
        })(
            <RadioGroup onChange={this.onWayChange}>
                {obtainTypes.map(r =>
                    <Radio style={{ display: 'block' }} key={r.key} value={r.type}>{r.title}
                        <Tooltip placement="bottomLeft" title={<div>{r.desc}<br /><b>示例：</b>{r.demo}</div>}>
                            <span className="help-tips pushl">
                                <Icon type="info-circle" />
                            </span>
                        </Tooltip>
                    </Radio>
                )}
            </RadioGroup>);
        return [
            {
                title: '获得项',
                dataIndex: 'getSource',
                width: 80,
                className: "ant-table-th-center",
                render: (text, record) => {
                    return <span>{record.obtainName.substr(0, 2)}</span>
                }
            },
            {
                title: '说明',
                dataIndex: 'desc',
                width: 200,
                className: "ant-table-th-center",
                render: (text, record) => {
                    return <span>{record.description}</span>
                }
            },
            {
                title: '是否启用',
                dataIndex: 'Enable',
                width: 200,
                render: (text, record, index) => {
                    if ("order" == record.obtainType) {
                        return <span>
                            <span>
                                <Checkbox defaultChecked={record.isOpen == 1} onChange={(e) => { this.onObtainIsOpenChange(e, record) }}></Checkbox><br />

                                {/* 货到付款功能被取消*/}
                                {/*<FormItem>*/}
                                    {/*{grpIntegralField} <span>（货到付款订单）</span>*/}
                                {/*</FormItem>*/}
                            </span>
                        </span>
                    } else {
                        return <span><Checkbox defaultChecked={record.isOpen == 1} onChange={(e) => { this.onObtainIsOpenChange(e, record) }} ></Checkbox><br /></span>
                    }
                },
                className: "ant-table-th-center"
            },
            {
                title: '奖励积分',
                dataIndex: 'obtainVal',
                width: 450,
                className: "ant-table-th-center",
                render: (obtainVal, row, index) => {
                    //积分获得项类型：order：交易，login：登录，register：注册
                    if ("order" == row.obtainType){
                        return <div className="t-left">
                            <Row>
                                <Col span="10">
                                    {orderObtainTypeField}
                                </Col>
                                <Col span="14">
                                    <div className="integral-set">
                                        {this.renderIntrgralContent(settingInfo, orderObtainVal)}
                                    </div>
                                </Col>
                            </Row>
                        </div>
                    } else {
                        return <span><InputNumber min={0} max={99999} step={500} defaultValue={obtainVal} style={{ width: "100px" }} onChange={(value) => { this.onObtainValChange(value, row) }} />（0-99999）</span>
                    }
                }
            },
        ];
    }

    renderIntrgralContent = (settingInfo, orderObtainVal) => {
         //商品售价比例设置输入框
        let obtainPercentInput = <InputNumber
                                    min={0} 
                                    max={100}
                                    style={{ width: '100px' }}
                                    onChange={this.changeOrderObtainVal}
                                    value={orderObtainVal} 
                                />;
        

        switch (settingInfo.get("orderObtainType")) {
            case 1:
                //商品售价比例
                return (
                    <span>
                        商品售价比例：
                        {obtainPercentInput}
                        %
                    </span>
                )
            case 2:
                //固定积分
                return (
                    <div>
                        商品固定积分设置<a href={$CONST_HOST['v_app_web']+"/#/mall/goods/price?_k="+this.context.location.key} className="pushl">去设置</a>
                    </div>
                )
            case 3:
                //混合模式
                return (
                    <div>
                        商品售价比例：{obtainPercentInput} %<br />
                        商品固定积分设置<a href={$CONST_HOST['v_app_web']+"/#/mall/goods/price?_k="+this.context.location.key} className="pushl">去设置</a>
                    </div>
                )
            default:
                return null
        }
    }
    /**
     * 商品售价比例设置
     */
    changeOrderObtainVal = ( value ) => {
        let { onRuleUpdate, orderObtain } = this.props;
        //保留2位小数
        value = float.floor(value);
        onRuleUpdate(orderObtain.set('obtainVal',value));
    }
    /**
     * 显示或隐藏更多的选项
     */
    toggleShow = (checked) => {
        let { onSettingUpdate } = this.props;
        onSettingUpdate(Immutable.fromJS({ isOpenSetting: checked ? 1 : 0 }));
    }
}

export default IntegralForm;